package br.org.group.web.fortunes;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import br.org.group.android.dao.FortunesDAO;
import br.org.group.android.dao.PMF;

public class FortunesWebProvider {

	private List<FortunesDAO> fortunes;
	private PersistenceManager pm = PMF.get().getPersistenceManager();

	public FortunesDAO getFortune(int id) throws IOException {
		pm = PMF.get().getPersistenceManager();

		if (id < 0) {
			id = id * -1;
		}
		
		if (id == 0) {
			id = 1;
		}

		String query = "select from " + FortunesDAO.class.getName() + " where id == " + (id + 1);
		fortunes = (List<FortunesDAO>) pm.newQuery(query).execute();

		if (fortunes.isEmpty()) {
			pm.close();
			return null;
		} else {
			for (FortunesDAO f : fortunes) {
				pm.close();
				return f;
			}
		}
		pm.close();
		return null;
	}

}
